import os
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk  # 导入PIL库用于图像处理
from ui.BasePage import BasePage

class ResultAnalysisPage(BasePage):
    """结果分析页面：展示分类指标表格 + 总体评估指标"""
    def __init__(self, parent, controller):
        super().__init__(parent, controller)
        
        # 1. 分类指标表格：用 Treeview 实现
        #self.init_classification_table()
        # 2. 总体评估指标：用 Label 展示
        #self.init_overall_metrics()
        
        
        # 加载并显示图片
        self.load_and_display_image()

    def load_and_display_image(self):
        try:
            # 获取当前脚本所在目录
            script_dir = os.path.dirname(os.path.abspath(__file__))
            dir  = os.path.dirname(os.path.dirname(script_dir))
            # 拼接图片的绝对路径
            image_path = os.path.join(dir, "resources", "image", "1.png")

            # 打开图片
            image = Image.open(image_path)
            
            # 调整图片大小以适应窗口（可选）
            max_width = 800
            max_height = 600
            image.thumbnail((max_width, max_height))
            
            # 将图片转换为Tkinter可用的格式
            self.photo = ImageTk.PhotoImage(image)
            
            # 创建显示图片的标签（添加到self.frame上）
            image_label = ttk.Label(self.frame, image=self.photo)
            image_label.pack(pady=10)
            
            # 添加图片路径标签（添加到self.frame上）
            path_label = ttk.Label(self.frame, text=f"图片路径: {image_path}", font=("微软雅黑", 10))
            path_label.pack(pady=5)
            
        except Exception as e:
            # 处理可能的错误（添加到self.frame上）
            error_label = ttk.Label(self.frame, text=f"加载图片时出错: {str(e)}", foreground="red")
            error_label.pack(pady=20)

    """ 
        非Image的方法
    """
    def init_classification_table(self):
        """初始化分类指标表格（精确率、召回率、F1、样本数）"""
        table_frame = ttk.Frame(self.frame)
        table_frame.pack(fill=tk.X, padx=10, pady=10)

        # 表格列配置
        columns = ("index", "category", "precision", "recall", "f1", "sample")
        self.tree = ttk.Treeview(
            table_frame,
            columns=columns,
            show="headings",
            selectmode="browse",
            height=10  # 控制表格显示行数
        )

        # 设置表头（移除 width 参数）
        self.tree.heading("index", text="#")
        self.tree.heading("category", text="类别")
        self.tree.heading("precision", text="精确率")
        self.tree.heading("recall", text="召回率")
        self.tree.heading("f1", text="F1分数")
        self.tree.heading("sample", text="样本数")

        # 使用 column() 方法设置列宽
        self.tree.column("index", width=40, anchor="center")
        self.tree.column("category", width=120, anchor="center")
        self.tree.column("precision", width=80, anchor="center")
        self.tree.column("recall", width=80, anchor="center")
        self.tree.column("f1", width=80, anchor="center")
        self.tree.column("sample", width=80, anchor="center")

        # 填入数据（可根据实际业务逻辑动态替换）
        data = [
            (1, "正常", 1.0000, 1.0000, 1.0000, 50),
            (2, "内圈故障0.007", 1.0000, 1.0000, 1.0000, 50),
            (3, "内圈故障0.014", 1.0000, 1.0000, 1.0000, 50),
            (4, "内圈故障0.021", 1.0000, 1.0000, 1.0000, 50),
            (5, "外圈故障0.007", 0.9800, 1.0000, 0.9900, 50),
            (6, "外圈故障0.014", 1.0000, 1.0000, 1.0000, 50),
            (7, "外圈故障0.021", 1.0000, 1.0000, 1.0000, 50),
            (8, "滚动体故障0.007", 0.9900, 1.0000, 0.9800, 50),
            (9, "滚动体故障0.014", 1.0000, 1.0000, 1.0000, 50),
            (10, "滚动体故障0.021", 1.0000, 1.0000, 1.0000, 50),
        ]
        for item in data:
            self.tree.insert("", tk.END, values=item)

        self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        # 滚动条（适配表格高度超出时）
        scrollbar = ttk.Scrollbar(
            table_frame,
            orient="vertical",
            command=self.tree.yview
        )
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.configure(yscrollcommand=scrollbar.set)

    def init_overall_metrics(self):
        """初始化总体评估指标展示"""
        metrics_frame = ttk.Frame(self.frame)
        metrics_frame.pack(fill=tk.X, padx=10, pady=5)

        # 可根据实际数据动态生成，这里先写死示例值
        metrics = {
            "准确率": 0.996,
            "宏平均准确率": 0.997,
            "平均召回率": 1.000,
            "平均F1分数": 0.996,
            "加权平均F1分数": 0.997,
        }

        for idx, (name, value) in enumerate(metrics.items()):
            row_frame = ttk.Frame(metrics_frame)
            row_frame.pack(fill=tk.X, pady=2)
            
            ttk.Label(row_frame, text=f"{name}：", width=12, anchor="w").pack(side=tk.LEFT)
            ttk.Label(row_frame, text=f"{value:.4f}", width=12, anchor="w").pack(side=tk.LEFT)